/* KeyHandler.h
Copyright (c) 2008 Michael Zahniser
Please note the license terms (MIT license) at the end of this document.

Header file for the KeyHandler class, which stores a set of functions to be
called for different key presses.
*/

#ifndef __SDL_KEY_HANDLER_H__
#define __SDL_KEY_HANDLER_H__

#include "SDL.h"

#include <map>

using std::map;



template <class Client>
class KeyHandler {
public:
	// This is the prototype for all key handlers in the client.
	typedef void (Client::*MemFun)(SDLKey key, SDLMod mod);

	// Use this to define a handler that accepts any modifiers.
	static const SDLMod ANY_MOD = static_cast<SDLMod>(0xFFFF);


public:
	KeyHandler();

	// Set the object whose functions will respond to the key events.
	void SetClient(Client *client);

	// Set the handler for the given key and set of modifiers.
	void SetHandler(SDLKey key, int mod, MemFun fun);
	void SetHandler(char key, int mod, MemFun fun);
	// Alternate syntax for setting a handler:
	// handler(key, mod) = fun;
	MemFun &operator()(SDLKey key, int mod);
	MemFun &operator()(char key, int mod);

	// Handle the given key press.
	// Returns true if the key was handled. The key will always be handled
	// unless there is no default handler for a key with its modifiers.
	bool Handle(SDLKey key, SDLMod mod);
	

private:
	// Handle the exact key code given. Return true if handled.
	bool HandleCode(SDLKey key, SDLMod mod, Uint32 encoded);
	// Convert the given key and modifier into the format used by the handler map.
	static Uint32 Encode(SDLKey key, SDLMod mod);


private:
	map<Uint32, MemFun> handler;
	typedef typename map<Uint32, MemFun>::iterator HandlerIt;

	Client *client;
};



// This is a templated class, so all the functions must be in the header.
#include "KeyHandler.cpp"

#endif

/* Copyright (c) 2008 Michael Zahniser

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. */
